# -*- coding: utf-8 -*-

import sys
import os
import socket
import yaml

host = 'localhost'
port = 6633

def get_version(program):
	s.send('VERSION %s' % program)
	data = s.recv(1024)
	return data.strip()
	
def get_desc(program):
	s.send('DESC %s' % program)
	data = s.recv(1024)
	return data.strip()
	
def get_list(program):
	s.send('LIST %s' % program)
	data = s.recv(1024)
	return data.strip().split('\r\n')

def get_size(program, file):
	s.send('SIZE %s %s' % (program, file))
	data = s.recv(1024)
	return data.strip()

def get_action(program, file):
	s.send('ACTION %s %s' % (program, file))
	data = s.recv(1024)
	return data.strip()
	
def get_file(program, file, path):
	size = get_size(program, file)
	action = get_action(program, file).replace(' ', '').split(',')
	
	s.send('GET %s %s' % (program, file))
	data = s.recv(int(size))
	
	for act in action:
		if act == 'none':			
			f = open(file, 'wb')
			f.write(data)
			f.close()
			
		if act == 'replace':
			file = path + file
			f = open(file, 'wb')
			f.write(data)
			f.close()
			
		if act == 'exec':
			os.execvp(file, ())
		
def send_ok(program, file):
	s.send('OK %s %s' % (program, file))

def send_error(program, file):
	s.send('ERROR %s %s' % (program, file))

f = open('config.yaml', 'r')
config = yaml.load(f)
f.close()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

for program in config:
	version = get_version(program)
	print '%s' % program
	
	if int(version) > int(config[program]['version']):
		print 'update needed'
		print 'you version %s available %s' % (config[program]['version'], version)
		print '%s\n' % get_desc(program)
		
		for file in get_list(program):			
			get_file(program, file, config[program]['files'][file]['path'])
			print 'GET %s' % file
		
		send_ok(program, file)
		config[program]['version'] = version
		
		f = open('config.yaml', 'w')
		yaml.dump(config, f)
		f.close()
	else:
		print 'you up to date\n'

s.close()
